<template>
	<view class="page-wrap">
		<view class="share-guide" v-if="onshare">
			<button type="primary" class="cu-btn bg-blue" @click="changeOnshare">知道了</button>
		</view>
		<view class="top-bg">
		</view>
		<view class="join-number">
			<text v-if="total">
				已参与
				<text class="number">{{total}}</text>人
			</text>
		</view>
		<view class="e-charts">
			<!-- 			<uni-echart class="uni-ec-charts" id="uni-ec-canvas" @click="echarts.onClick" :prop="ecOption">
			</uni-echart> -->
			<view :prop="ecOption" id="echarts" class="e-charts">
			</view>
		</view>
		<view class="button" @click.stop="showModal('editInfo')" v-if="wxUserInfo&&wxUserInfo.unionid">
		</view>
		<!-- 		<view class="button share-btn">
			<button class="cu-btn bg-gradual-orange"  @click="changeOnshare">分享</button>
		</view> -->
		<view class="cu-modal bottom-modal" @click="hideModal" :class="{show:modalName==='editInfo'}">
			<view class="cu-dialog" @click.stop="">
				<view class="edit-info">
					<view class="form-item">
						<view class="label">
							选择你的身份
						</view>
						<bx-radio-group class="radio-group" v-model="typeRadio" mode="button">
							<bx-radio v-for="item in radioList" :key="item" :name="item">{{ item}}</bx-radio>
						</bx-radio-group>
					</view>
					<view class="form-item" v-if="typeRadio==='为家乡'||typeRadio==='家乡'">
						<view class="label">
							选择家乡节点
						</view>
						<view class="">
							<view class="form-input" @click="showModal('areaSelector')">
								<text class="text">
									{{selectArea.name_path||'点击选择地区'}}
								</text>
								<text class="cuIcon-close margin-left" v-if="selectArea.name_path"
									@click.stop="clearAreaInfo"></text>
							</view>
						</view>
					</view>
					<view class="form-item" v-if="typeRadio==='为单位'||typeRadio==='单位'">
						<view class="label">
							输入公司名称
						</view>
						<view class="">
							<view class="form-input">
								<input type="text" v-model="org_name" placeholder="请输入公司名称" @input="onInputCompany" />
								<text class="cuIcon-close" v-if="selectArea.name" @click.stop="clearAreaInfo"></text>
							</view>
						</view>
						<view class="company-list" v-if="companyList&&companyList.length>0">
							<view class="company-item" v-for="item in companyList" :key="item.id"
								@click="clickCompany(item)">
								{{item.org_name||''}}
							</view>
						</view>
					</view>
					<view class="button-box" v-if="wxUserInfo&&wxUserInfo.unionid">
						<!-- 				<button class="cu-btn bg-orange " :disabled="disabledButton" @click="presentFlower"
							v-if="!result||!result.id">点击献花</button> -->
						<button class="cu-btn bg-orange " :disabled="disabledButton"
							@click="presentFlower">点击献花</button>

					</view>
				</view>
			</view>
		</view>
		<view class="cu-modal bottom-modal" @click="hideModal" :class="{show:modalName=== 'areaSelector'}">
			<view class="cu-dialog" @click.stop="" v-if="modalName=== 'areaSelector'">
				<cascader-selector @clickTag="clickTag" :srvInfo="srvInfo" :order="areaOrder"
					@getCascaderValue="getCascaderValue">
				</cascader-selector>
			</view>
		</view>
	</view>
</template>

<script>
	import * as echarts from '@/static/echarts.js'
	const _jwx = require('jweixin-module');
	import chinaJson from '@/static/china.json'
	echarts.registerMap('china', chinaJson);
	let myChart = null
	let option
	export default {
		data() {
			return {
				onshare: false,
				areaOrder: [{
					colName: "city_code",
					orderType: "desc"
				}],
				total: 0, //活动参加人数
				modalName: "",
				wxUserInfo: "",
				typeRadio: "",
				srvInfo: {
					column: 'id',
					parentCol: 'pid',
					showCol: 'name',
					isTree: true,
					serviceName: 'srvportal_city_select',
					appNo: 'bxportal'
				},
				org_name: "",
				selectedCompany: {},
				companyList: [],
				selectArea: {},
				radioList: ['个人', '家乡', '单位'],
				cityValue: '',
				ecOption: {
					option: {}
				},
				locationInfo: {},
				result: null, //献花记录
				provinceList: [],
				shareUser: ""
			}
		},
		computed: {

			disabledButton() {
				if (this.typeRadio === '为家乡' || this.typeRadio === '家乡') {
					if (this.selectArea && this.selectArea.id) {
						return false
					} else {
						return true
					}
				} else if (this.typeRadio === '个人') {
					return false
				} else if (this.typeRadio === '为单位' || this.typeRadio === '单位') {
					return false
				} else {
					return true
				}
			}
		},
		methods: {
			changeOnshare() {
				this.onshare = !this.onshare
			},
			async getPresentResult(unionid) {
				let url = this.getServiceUrl('bxportal', 'srvportal_act_atd_rcd_select', 'select');
				let req = {
					"serviceName": "srvportal_act_atd_rcd_select",
					"colNames": ["*"],
					"condition": [{
						colName: "unionid",
						ruleType: 'eq',
						value: unionid
					}],
					"page": {
						"pageNo": 1,
						"rownumber": 1
					},
				}
				if (!unionid) {
					return
				}
				let res = await this.$http.post(url, req)
				if (res.data.state === 'SUCCESS' && res.data.data.length > 0) {
					this.result = res.data.data[0]
					this.setWXOption();
				}
			},
			async getUserInfo() {
				let url = this.$api.getUserInfo;
				let req = {
					serviceName: 'srvwx_basic_user_info_select',
					colNames: ['*'],
					condition: [{
						colName: 'app_no',
						ruleType: 'eq',
						value: this.$api.appNo.wxh5
					}]
				};
				let res = await this.$http.post(url, req);
				if (res.data.state === 'SUCCESS' && res.data.data.length > 0) {
					const userInfo = res.data.data[0];
					this.wxUserInfo = userInfo;
					// this.setWXOption();
					this.getPresentResult(userInfo.unionid)
				}
			},
			async presentFlower() {
				let userInfo = this.wxUserInfo
				if (userInfo && userInfo.unionid) {
					let url = this.getServiceUrl('bxportal', 'srvportal_act_atd_rcd_add', 'operate');
					let req = [{
						"serviceName": "srvportal_act_atd_rcd_add",
						"condition": [],
						"data": [{
							"act_no": "AT2106110001",
							hometown_id: this.selectArea.id,
							"user_no": userInfo.user_no || userInfo.unionid,
							share_user_no: uni.getStorageSync('shareUser') || this.shareUser,
							unionid: userInfo.unionid,
							"nick_name": userInfo.nickname,
							"atd_type": this.typeRadio,
							"lng": this.locationInfo.longitude,
							"lat": this.locationInfo.latitude
						}]
					}]
					let res = await this.$http.post(url, req)
					this.hideModal()
					if (res.data.state === 'SUCCESS') {
						if (
							Array.isArray(res.data.response) &&
							res.data.response.length > 0 &&
							res.data.response[0].response &&
							Array.isArray(res.data.response[0].response.effect_data) &&
							res.data.response[0].response.effect_data.length > 0
						) {
							uni.showToast({
								title: res.data.resultMessage,
							})
							this.result = res.data.response[0].response.effect_data[0]
						}
					} else {
						uni.showToast({
							title: res.data.resultMessage,
							icon: 'none'
						})
					}
				}
			},
			async getData() {
				let req = {
					"serviceName": "srvportal_city_select",
					"colNames": ["*"],
					"condition": [{
						colName: 'level',
						ruleType: 'eq',
						value: 1
					}],
					"page": {
						"pageNo": 1,
						"rownumber": 50
					},
				}
				let url = this.getServiceUrl('bxportal', 'srvportal_city_select', 'select');
				let res = await this.$http.post(url, req)
				if (Array.isArray(res.data.data) && res.data.data.length > 0) {
					// this.provinceList = res.data.data
					return res.data.data
				}
			},
			async buildOption() {
				myChart = echarts.init(document.getElementById('echarts'))
				let proData = await this.getData()
				// proData = proData.map(item => {
				// 	item.label = item.name
				// 	// item.label = item.name.replace('省', '').replace('市','')
				// 	return item
				// })

				var geoCoordMap = {
					// "陕西": [109.1162, 34.2004]
				};
				let obj = {}
				proData.forEach(item => {
					obj[item.name] = [item.lng, item.lat]
				})
				geoCoordMap = obj
				var data = [{
					name: "陕西",
					value: 80
				}];
				data = proData.map(item => {
					let obj = {}
					obj.name = item.name
					obj.value = item.total_count || 0
					return obj
				}).filter(item => item.value)
				this.total = data.reduce((pre, cur) => {
					return pre + cur.value
				}, 0)
				var max = 480,
					min = 9; // todo 
				var maxSize4Pin = 100,
					minSize4Pin = 20;

				var convertData = function(data) {
					var res = [];
					for (var i = 0; i < data.length; i++) {
						var geoCoord = geoCoordMap[data[i].name];
						if (geoCoord) {
							res.push({
								name: data[i].name,
								value: geoCoord.concat(data[i].value)
							});
						}
					}
					return res;
				};



				option = {
					tooltip: {
						trigger: 'item',
						formatter: function(params) {
							if (typeof(params.value)[2] == "undefined") {
								return params.name + ' : ' + params.value;
							} else {
								return params.name + ' : ' + params.value[2];
							}
						}
					},
					legend: {
						orient: 'vertical',
						y: 'bottom',
						x: 'right',
						data: ['pm2.5'],
						textStyle: {
							color: '#fff'
						}
					},
					visualMap: {
						show: false,
						min: 0,
						max: 500,
						left: 'left',
						top: 'bottom',
						text: ['高', '低'], // 文本，默认为数值文本
						calculable: true,
						seriesIndex: [1],
						inRange: {

						}
					},
					geo: {
						top: 0,
						bottom: 30,
						map: 'china',
						show: true,
						roam: true,
						label: {
							normal: {
								show: false
							},
							emphasis: {
								show: false,
							}
						},
						itemStyle: {
							areaColor: '#e12c32',
							normal: {
								areaColor: '#e12c32',
								borderColor: '#8d1b1f', //线
								shadowColor: '#83191d', //外发光
								shadowBlur: 20
							},
							emphasis: {
								areaColor: '#ff3239', //悬浮区背景
							}
						}
					},
					series: [{
							symbolSize: 5,
							label: {
								normal: {
									formatter: '{b}',
									position: 'right',
									show: true
								},
								emphasis: {
									show: true
								}
							},
							itemStyle: {
								normal: {
									color: '#fff'
								}
							},
							name: 'light',
							type: 'scatter',
							coordinateSystem: 'geo',
							data: convertData(data),

						},
						{
							type: 'map',
							map: 'china',
							geoIndex: 0,
							aspectScale: 0.5, //长宽比
							showLegendSymbol: false, // 存在legend时显示
							label: {
								normal: {
									show: false
								},
								emphasis: {
									show: false,
									textStyle: {
										color: '#fff'
									}
								}
							},
							roam: true,
							itemStyle: {
								areaColor: '#e12c32',
								normal: {
									areaColor: '#e12c32',
									borderColor: '#FFFFFF',
								},
								emphasis: {
									areaColor: '#83191d'
								}
							},
							animation: false,
							data: data
						},
						{
							name: 'Top 5',
							type: 'scatter',
							coordinateSystem: 'geo',
							symbol: 'pin',
							symbolSize: [50, 50],
							label: {
								normal: {
									show: true,
									textStyle: {
										color: '#fff',
										fontSize: 9,
									},
									formatter(value) {
										return value.data.value[2]
									}
								}
							},
							itemStyle: {
								normal: {
									// color: '#ff8f45', //标志颜色
									color: '#D8BC37', //标志颜色
								}
							},
							data: convertData(data),
							showEffectOn: 'render',
							rippleEffect: {
								brushType: 'stroke'
							},
							hoverAnimation: true,
							zlevel: 1
						},
					]
				};
				this.ecOption = option
				myChart.setOption(option);
			},
			clickCompany(e) {
				this.selectedCompany = e
				this.org_name = e.org_name
				this.companyList = []
			},
			onInputCompany(e) {
				let cond = null
				if (e.detail.value) {
					cond = [{
						colName: 'org_name',
						ruleType: 'like',
						value: e.detail.value
					}]
					this.selectCompany(cond)
				} else {
					this.companyList = []
				}
			},
			selectCompany(cond) {
				let url = this.getServiceUrl('bxportal', 'srvportal_org_mgmt_select', 'select');
				let req = {
					"serviceName": "srvportal_org_mgmt_select",
					"colNames": ["*"],
					"condition": cond || [],
					"page": {
						"pageNo": 1,
						"rownumber": 3
					},
				}
				this.$http.post(url, req).then(res => {
					if (Array.isArray(res.data.data)) {
						this.companyList = res.data.data
					}
				})
			},
			clearAreaInfo() {
				this.selectArea = {
					name: ''
				}
			},
			onClick(event, ownerInstance) {
				// 调用 service 层的方法
				ownerInstance.callMethod('onViewClick', {
					test: 'test'
				})
			},
			updateEcharts(newValue, oldValue, ownerInstance, instance) {
				// 监听 service 层数据变更
				myChart.setOption(newValue)
			},
			getCascaderValue(e) {
				this.clickTag(e, true)
			},
			clickTag(e, notLeaf = false) {
				// if (e && e.id) {
				if (e && (e.is_leaf === '是' || notLeaf)) {
					this.selectArea = e
					this.showModal('editInfo')
					this.setWXOption();
				}
			},
			showModal(name) {
				this.getLocationAuth()
				this.modalName = name
			},
			hideModal() {
				this.modalName = ''
			},
			getLocationAuth() {
				let linkurl = window.location.href.split('#')[0];
				let self = this
				let req = {
					serviceName: 'srvwx_app_signature_select',
					colNames: ['*'],
					condition: [{
							colName: 'app_no',
							ruleType: 'eq',
							value: this.$api.appNo.wxh5
						},
						{
							colName: 'page_url',
							ruleType: 'eq',
							value: linkurl
						}
					]
				};

				self.$http.post(self.$api.getSignature, req).then(res => {
					if (res.data.state === 'SUCCESS') {
						let resData = res.data.data[0];
						console.log('getSignature', resData);
						uni.setStorageSync('signatureInfo', resData);
						_jwx.config({
							debug: false, // 调试阶段建议开启
							appId: resData.appId, // APPID
							timestamp: resData.timestamp, // 时间戳timestamp
							nonceStr: resData.noncestr, // 随机数nonceStr
							signature: resData.signature, // 签名signature
							// 需要调用的方法接口
							jsApiList: ['checkJsApi',
								'openLocation',
								'getLocation'
							]
						});
						_jwx.ready(() => {
							_jwx.checkJsApi({
								jsApiList: [
									'getLocation'
								],
								success: function(res) {
									if (res.checkResult.getLocation == false) {
										alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
										return;
									}
								}
							});
							_jwx.getLocation({
								type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
								success: function(res) {
									var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
									var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
									var speed = res.speed; // 速度，以米/每秒计
									var accuracy = res.accuracy; // 位置精度
									self.locationInfo = res
								}
							});
						});
						_jwx.error(function(res) {
							console.log(res);
						});
					}
				});
			},
			setWXOption() {
				let linkurl = window.location.href.split('#')[0];
				let self = this
				let req = {
					serviceName: 'srvwx_app_signature_select',
					colNames: ['*'],
					condition: [{
							colName: 'app_no',
							ruleType: 'eq',
							value: this.$api.appNo.wxh5
						},
						{
							colName: 'page_url',
							ruleType: 'eq',
							value: linkurl
						}
					]
				};
				self.$http.post(self.$api.getSignature, req).then(res => {
					if (res.data.state === 'SUCCESS') {
						let resData = res.data.data[0];
						console.log('getSignature', resData);
						// linkurl = `/activity/?shareUser=${self.wxUserInfo.user_no || self.wxUserInfo.unionid}`
						linkurl = `${linkurl}?shareUser=${self.wxUserInfo.user_no || self.wxUserInfo.unionid}`
						uni.setStorageSync('signatureInfo', resData);
						_jwx.config({
							debug: false, // 调试阶段建议开启
							appId: resData.appId, // APPID
							timestamp: resData.timestamp, // 时间戳timestamp
							nonceStr: resData.noncestr, // 随机数nonceStr
							signature: resData.signature, // 签名signature
							// 需要调用的方法接口
							jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData',
								'onMenuShareTimeline', 'onMenuShareAppMessage'
							]
						});
						_jwx.ready(() => {
							_jwx.updateAppMessageShareData({
								//自定义“分享给朋友”及“分享到QQ”按钮的分享内容
								imgUrl: 'https://wx2.100xsys.cn/activity/static/100years.png' ||
									'https://srvms.100xsys.cn:443/file/download?fileNo=20200306184125960100', // 分享图，默认当相对路径处理，所以使用绝对路径的的话，“http://”协议前缀必须在。
								desc: `2021年7月1日是中国共产党成立100周年纪念日。2021年3月23日，中宣部介绍中国共产党成立100周年庆祝活动八项主要内容。3月24日，中宣部发布中国共产党成立100周年庆祝活动标识。4月20日，由中共中央宣传部、文化和旅游部、中国文学艺术界联合会共同举办的庆祝中国共产党成立100周年优秀舞台艺术作品展演开幕。
2021年6月26日，庆祝中国共产党成立100周年活动新闻中心在北京梅地亚中心正式运行。6月13日，庆祝中国共产党成立100周年大会首次综合演练圆满结束`, // 摘要,如果分享到朋友圈的话，不显示摘要。
								title: '建党100周年献花助力', // 分享卡片标题
								// link:  window.location.href, // 分享出去后的链接，这里可以将链接设置为另一个页面。
								link: linkurl, // 分享出去后的链接，这里可以将链接设置为另一个页面。
								success: function() {
									// self.saveShareRecord('朋友');
								},
								cancel: function() {
									// 用户取消分享后执行的回调函数
									// //// alert('分享失败')
								}
							}); // 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
							_jwx.updateTimelineShareData({
								imgUrl: 'https://wx2.100xsys.cn/activity/static/100years.png' ||
									'https://srvms.100xsys.cn:443/file/download?fileNo=20200306184125960100', // 分享图，默认当相对路径处理，所以使用绝对路径的的话，“http://”协议前缀必须在。
								desc: `2021年7月1日是中国共产党成立100周年纪念日。2021年3月23日，中宣部介绍中国共产党成立100周年庆祝活动八项主要内容。3月24日，中宣部发布中国共产党成立100周年庆祝活动标识。4月20日，由中共中央宣传部、文化和旅游部、中国文学艺术界联合会共同举办的庆祝中国共产党成立100周年优秀舞台艺术作品展演开幕。
2021年6月26日，庆祝中国共产党成立100周年活动新闻中心在北京梅地亚中心正式运行。6月13日，庆祝中国共产党成立100周年大会首次综合演练圆满结束`, // 摘要,如果分享到朋友圈的话，不显示摘要。
								title: '建党100周年献花助力', // 分享卡片标题
								link: linkurl, // 分享出去后的链接，这里可以将链接设置为另一个页面。
								success: function() {
									// 分享成功后的回调函数
									// //// alert('分享成功')
									// self.saveShareRecord('朋友圈');
								},
								cancel: function() {
									// 用户取消分享后执行的回调函数
									// //// alert('分享失败')
								}
							});
						});
						_jwx.error(function(res) {
							console.log(res);
						});
					} else {}
				});
			},
			async addViewRecord() {
				let url = this.getServiceUrl('bxportal', 'srvportal_share_visit_log_add', 'operate');
				let req = [{
					"serviceName": "srvportal_share_visit_log_add",
					"condition": [],
					"data": [{
						"act_no": "AT2106110001",
						"user_no": this.wxUserInfo.user_no,
						'share_url':'',
						"nick_name":  this.wxUserInfo.nickname,
						"unionid":  this.wxUserInfo.unionid,
						"profile_url":  this.wxUserInfo.headimgurl,
					}]
				}]
				this.$http.post(url,req)
			},
		},
		onLoad(option) {
			if (option.shareUser) {
				this.shareUser = option.shareUser
				uni.setStorageSync('shareUser', option.shareUser)
			}
		},
		mounted() {
			if (this.$route?.query?.shareUser) {
				this.shareUser = this.$route.query.shareUser
				uni.setStorageSync('shareUser', this.$route.query.shareUser)
			}

			this.getUserInfo()
			setTimeout(() => {
				this.buildOption()
				let shareUser = uni.setStorageSync('shareUser') || this.shareUser

				if (shareUser) {

				}

			}, 200)

		}
	}
</script>

<style lang="scss" scoped>
	.page-wrap {
		height: 100vh;
		background-color: #8a1b1f;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-image: url(../../../static/img/100year_bg_full.png);
		position: relative;

		.share-guide {
			position: absolute;
			top: 0;
			left: 0;
			z-index: 20;
			width: 100vw;
			height: 100vh;
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-image: url(../../../static/share-guide.jpg);
			display: flex;
			justify-content: center;
			align-items: center;

			.cu-btn {
				width: 40%;
				margin-top: 250rpx;
			}
		}

		.top-bg {
			background-image: url(../../../static/img/100year_top.png);
			background-size: 100%;
			width: 100vw;
			height: 520rpx;
			// margin-top: -20rpx;
		}

		.join-number {
			color: #fff;
			font-size: 20px;
			text-align: center;
			min-height: 50rpx;

			.number {
				font-size: 28px;
				font-weight: bold;
				margin: 0 10rpx;
			}
		}

		.button {
			width: 100vw;
			height: 350rpx;
			background-size: 100%;
			background-image: url(../../../static/img/100year_button_1.png);
			position: absolute;
			bottom: 0;

			&.share-btn {
				background-image: none;
				display: flex;
				align-items: center;
				justify-content: center;

				.cu-btn {
					margin: 0 auto;
					width: 50%;
				}
			}
		}

		.edit-info {
			min-height: 30vh;
			padding: 30rpx;

			.form-item {
				.form-input {
					border: 1px solid #f1f1f1;
					padding: 20rpx 40rpx;
					display: flex;
					align-items: center;

					.text {
						flex: 1;
					}
				}
			}

			.label {
				padding: 10rpx 0;
			}
		}

	}

	.company-list {
		padding: 20rpx;
		margin: 10rpx 20rpx;
		box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
	}

	.e-charts {
		width: 100%;
		height: 600rpx;
		margin-top: -20rpx;

		.uni-ec-charts {
			width: 100%;
			height: 100%;
		}
	}

	.button-box {
		padding: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 30px;
	}
</style>
